//1、all 
// 接收一个Promise数组，数组中如有非Promise项，则此项当作成功
//如果所有Promise都成功，则返回成功结果数组
//如果有一个Promise失败，则返回这个失败结果

function all(promises){
    let result = []
    let count = 0
     
    return new MyPromise((resolve,reject) => {
        const addData = (index,value) => {
            result[index] = value
            count ++ 
            if(count === promises.length) { 
                resolve(result) 
            }
        }

        promises.forEach((promise,index) => {
            if(promise instanceof MyPromise){
                promise.then(res =>{
                    addData(index,res)
                },err => reject(err))
            } else {
                addData(index,promise)
            }
        })
    })
}

//1、race 
//接收一个Promise数组，数组中如有非Promise项,则此项当作成功
//哪个Promise最快得到结果，就返回哪个结果，无论成功失败

function race(promises){
    return new MyPromise((resolve,reject)=>{
        promises.forEach(promise=> {
            if(promise instanceof MyPromise){
                promise.then( res=>{
                    resolve(res)
                },err => reject(err))
            } else {
                resolve(promise)
            }
        })
    })
}

//3、allSettled
//接收一个Promise数组，数组中有非Promise项，则此项当作成功
//把每一个Promise的结果，集合成数组，返回

function allSettled(promises){
    return new Promise((resolve)=>{
        const res = []
        let count = 0

        const addData = (status,value,index)=>{
            res[index] = {status,value}
            count ++ 
            if(count === promises.length) resolve(res)
        }

        promises.forEach((promise,index)=>{
            if(promise instanceof MyPromise){
                promise.then(res=>{
                    addData('fulfilled', res, index)
                },err => { addData('rejected', err, index)})
            } else {
                addData('fulfilled', promise, index)
            }
        })
    })
}

//4、any 
// any与all 相反  接收一个Promise数组，数组中如有非Promise，则此项当作成功
//如果有一个Promise成功，则返回这个成功结果
//如果所有Promise都失败，则报错

function any(promises){
    return new Promise((resolve,reject) => {
        let count = 0
        promises.forEach(promise => {
            promise.then(res=>{
                resolve(res)
            },err => {
                count ++ 
                if(count === promises.length){
                    reject(new AggregateError('All promises were rejected'))
                }
            })
        })
    })
}